<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="接单状态" prop="workerConfirmstatus">
        <el-select v-model="queryParams.workerConfirmstatus" placeholder="请选择" clearable>
          <el-option
            v-for="dict in dict.type.worker_confirmstatus"
            :key="dict.value"
            :label="dict.label"
            :value="parseInt(dict.value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单合同号" prop="contractCode">
        <el-input
          v-model="queryParams.contractCode"
          placeholder="请输入订单合同号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="生产工单号" prop="contractCode">
        <el-input
          style="width: 300px;"
          v-model="queryParams.workerorderCode"
          placeholder="请输入生产订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发送状态" prop="sendStatus">
        <el-select v-model="queryParams.sendStatus" placeholder="请选择" filterable clearable>
          <el-option
            v-for="item in sendStatusList"
            :key="item.sendStatus"
            :label="item.sendStatusDesc"
            :value="item.sendStatus"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="产地" prop="factoryId">
        <el-select v-model="queryParams.factoryId" placeholder="请选择" filterable clearable @change="factoryChange">
          <el-option v-for="team in factoryList" :key="team.deptId" :label="team.deptName" :value="team.deptId" />
        </el-select>
      </el-form-item>
      <el-form-item label="班组" prop="teamId">
        <el-select v-model="queryParams.teamId" placeholder="请选择" clearable>
          <el-option v-for="team in teamList" :key="team.deptId" :label="team.deptName" :value="team.deptId" />
        </el-select>
      </el-form-item>
      <el-form-item label="接单日期" prop="submitDate">
        <el-date-picker
          v-model="submitDateRange"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions">
        </el-date-picker>
      </el-form-item>
      <!--<el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="multiple"
          @click="handleReceive"
          v-hasPermi="['order:workorder:edit']"
        >接单</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading"
              border style="width:100%;" :data="workorderList" @selection-change="handleSelectionChange" :resizable="true">
      <el-table-column type="selection" width="55" align="center" :selectable="handleDisable"/>
      <el-table-column label="订单日期" align="center" prop="orderDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单合同号" align="center" prop="contractCode" width="150"/>
      <el-table-column label="订单号" align="center" prop="orderCode"  width="130"/>
      <el-table-column label="工单号" align="center" prop="workerorderCode" width="190" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span class="custom-cell">{{ scope.row.workerorderCode }}</span>
        </template>
      </el-table-column>
      <el-table-column label="客户名称" align="center" prop="customName" />
      <el-table-column label="产品名称" align="center" prop="bomName"  width="170" :show-overflow-tooltip="true"/>
      <el-table-column label="产品编码" align="center" prop="bomCode"  width="110"/>
      <el-table-column label="规格型号" align="center" prop="productStandard" width="160" />
      <el-table-column label="产品单位" align="center" prop="productUnit" :show-overflow-tooltip="true" />
      <el-table-column label="产品数量" align="center" prop="workerOrdernum" />
      <el-table-column label="样品数量" align="center" prop="sampleNum" />
      <el-table-column label="分厂名称" align="center" prop="factoryName" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="班组名称" align="center" prop="teamName" />
      <el-table-column label="接单时间" align="center" prop="recvTime" width="160">
        <template slot-scope="scope">
          <span>{{ formatDate(scope.row.recvTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发生金蝶时间" align="center" prop="pushTime" width="160">
        <template slot-scope="scope">
          <span>{{ formatDate(scope.row.pushTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="金蝶状态" align="center" prop="sendStatus" width="100" >
        <template slot-scope="scope">
          <div v-if="scope.row.sendStatus==='PENDING'"><el-tag>待发送</el-tag></div>
          <div v-else-if="scope.row.sendStatus==='PROCESSING'"><el-tag type="warning">发送中</el-tag></div>
          <div v-else-if="scope.row.sendStatus==='FINISHED'"><el-tag type="success">发送完成</el-tag></div>
          <div v-else-if="scope.row.sendStatus==='FAILED'"><el-tag type="danger">发送失败</el-tag></div>
          <div v-else-if="scope.row.sendStatus==='PAUSE'"><el-tag type="info">发送暂停</el-tag></div>
          <div v-else><el-tag v-if="scope.row.sendStatus!=null" type="info">{{scope.row.sendStatus}}</el-tag></div>
        </template>
      </el-table-column>
      <el-table-column label="错误原因" align="center" prop="errorMessage" >
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.errorMessage">
            <div class="ellipsis-text">{{ scope.row.errorMessage }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="库存情况" align="center" prop="storeStatus" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.store_status" :value="scope.row.storeStatus" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="scope.row.workerConfirmstatus==0"
            @click="handleReceive(scope.row)"
            v-hasPermi="['order:workorder:edit']"
          >接单</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="scope.row.workerConfirmstatus==0"
            @click="handleReturn(scope.row)"
            v-hasPermi="['order:workorder:edit']"
          >驳回</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="scope.row.workerConfirmstatus==1"
            @click="handlePushKingdee(scope.row)"
            v-hasPermi="['order:workorder:edit']"
          >手工推金蝶</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
  import { listWorkorder, getWorkorder, receiveWorkOrder, handlePushKingdee, returnWorkOrder,addWorkorder, updateWorkorder } from "@/api/sm/order/workorder";
  import { listTeam,listFactory } from "@/api/system/dept";
  import moment from "moment";

  const parseTime = function(time) {
    const values = (time || '').split(':');
    if (values.length >= 2) {
      const hours = parseInt(values[0], 10);
      const minutes = parseInt(values[1], 10);

      return {
        hours,
        minutes
      };
    }
    /* istanbul ignore next */
    return null;
  };
  export default {
    name: "Workorder",
    dicts: ['workerorder_type','worker_confirmstatus'],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 订单工单信息表格数据
        workorderList: [],
        factoryList: [],
        teamList: [],
        sendStatusList: [
          {"sendStatus": "PENDING", "sendStatusDesc": "待发送"},
          {"sendStatus": "PROCESSING", "sendStatusDesc": "发送中"},
          {"sendStatus": "FINISHED", "sendStatusDesc": "发送完成"},
          {"sendStatus": "FAILED", "sendStatusDesc": "发送失败"},
        ],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          productName: null,
          orderCode: null,
          contractCode: null,
          workOrderCode: null,
          teamName: null,
          teamId: null,
          teamCode: null,
          workerConfirmstatus: 0,
          workerOrderstatus: null,
          planStatus: null,
          workerOrdertype: null,
          workerOrdertypes: null,
          sendStatus: null,
        },
        // 表单参数
        form: {},
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        submitDateRange: null,
        // 表单校验
        rules: {
          workerOrdertype: [
            { required: true, message: "工单类型 1成品工单 2半成品工单不能为空", trigger: "change" }
          ],
          orderCode: [
            { required: true, message: "订单编码不能为空", trigger: "blur" }
          ],
          productId: [
            { required: true, message: "订单产品ID不能为空", trigger: "blur" }
          ],
          planStatus: [
            { required: true, message: "排产状态1：待排产 2已排产 3不可排产不能为空", trigger: "change" }
          ],
          feedingNum: [
            { required: true, message: "投料数量不能为空", trigger: "blur" }
          ],
        }
      };
    },
    created() {
      this.getList();
      this.getFactoryList();
    },
    methods: {
      dateStrings() {
        if (this.submitDateRange && this.submitDateRange.length === 2) {
          return this.submitDateRange.map(date => moment(date).format('YYYY-MM-DD'));
        }
        return ['', ''];
      },
      getDefaultDateRange() {
        const today = new Date();
        const tomorrow = new Date(today);
        tomorrow.setDate(tomorrow.getDate());

        // 将日期格式化为 yyyy-MM-dd
        const formatDate = (date) => {
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');
          return `${year}-${month}-${day}`;
        };

        return [formatDate(today), formatDate(tomorrow)];
      },
      formatDate (isoString) {
        if (!isoString) {
          return null;
        }
        const date = new Date(isoString);

        // 获取年、月、日、时、分、秒
        const year = date.getFullYear();
        const month = ('0' + (date.getMonth() + 1)).slice(-2); // 月份从0开始，需要加1并补零
        const day = ('0' + date.getDate()).slice(-2); // 补零
        const hours = ('0' + date.getHours()).slice(-2); // 补零
        const minutes = ('0' + date.getMinutes()).slice(-2); // 补零
        const seconds = ('0' + date.getSeconds()).slice(-2); // 补零

        // 拼接成 yyyy-MM-dd hh:mm:ss 格式
        const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

        return formattedDate;
      },
      /** 查询订单信息列表 */
      getFactoryList() {
        this.loading = true;
        listFactory({"level":2}).then(response => {
          this.factoryList = response.data;
          // this.queryParams.factoryId = this.factoryList[0].deptId;
          //this.getTeamList(this.queryParams.factoryId);
          this.teamList = [];
          this.loading = false;
        });
      },
      factoryChange(){
        this.getTeamList(this.queryParams.factoryId);
      },
      /** 查询订单信息列表 */
      getTeamList(parentId) {
        this.loading = true;
        listTeam({"parentId":parentId}).then(response => {
          this.teamList = response.data;
          this.loading = false;
        });
      },
      handleDisable(row, index) {
        if (row.workerConfirmstatus == '1' || row.headsterRecStatus=='0') {
          return false
        } else {
          return true
        }
      },
      /** 查询订单工单信息列表 */
      getList() {
        if (this.submitDateRange) {
          let beginEndTime = this.dateStrings();
          this.queryParams.beginTime = beginEndTime[0];
          this.queryParams.endTime = beginEndTime[1];
        }
        this.loading = true;
        this.queryParams.planStatus = 1;
        this.queryParams.workerOrdertypes = "1,3";
        listWorkorder(this.queryParams).then(response => {
          this.workorderList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          workerOrdertype: null,
          orderCode: null,
          productId: null,
          workerorderCode: null,
          bomCode: null,
          bomName: null,
          factoryName: null,
          factoryId: null,
          factoryCode: null,
          teamName: null,
          teamId: null,
          teamCode: null,
          workerOrdernum: null,
          workerConfirmstatus: null,
          workerOrderstatus: null,
          planStatus: null,
          planFinishdate: null,
          planDesc: null,
          feedingNum: null,
          createDate: null,
          creator: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 手工推金蝶 */
      handlePushKingdee(row) {
        const start = Date.now();
        const ids = row.id || this.ids;
        let loading = this.$loading({
          lock: true,
          text: '手工推金蝶工单中，请耐心稍等～',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        this.$modal.confirm('确认手工推金蝶工单吗？').then(function() {
          return handlePushKingdee(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess(`手工推金蝶成功,耗时=${(Date.now()-start)/1000}秒`);
          loading.close();
        }).catch(() => {
          loading.close();
        });
      },
      /** 驳回操作 */
      handleReturn(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('确认驳回工单？').then(function() {
          return returnWorkOrder(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("驳回成功");
        }).catch(() => {});
      },
      /** 接单操作 */
      handleReceive(row) {
        const start = Date.now();
        let loading = this.$loading({
          lock: true,
          text: '接单中，请耐心稍等～',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        const ids = row.id || this.ids;
        this.$modal.confirm('确认接收工单？').then(function() {
          return receiveWorkOrder(ids);
        }).then(() => {
          this.getList();
          this.loading = false;
          this.$modal.msgSuccess(`接单确认成功,耗时=${(Date.now()-start)/1000}秒`);
          loading.close();
        }).catch(() => {
          loading.close();
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('order/workorder/export', {
          ...this.queryParams
        }, `workorder_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>

<style scoped lang="scss">
  .custom-cell {
    font-size: 12px; /* 设置合适的字体大小 */
  }
  .ellipsis-text {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
</style>
